package bsc.war.handler;

import bsc.ejb.entity.Comparator;
import bsc.ejb.entity.DimensionalCut;
import bsc.ejb.entity.Person;
import bsc.ejb.entity.Pointer;
import bsc.ejb.entity.ScoreDomain;
import bsc.ejb.metadata.Colorimetry;
import bsc.ejb.metadata.Comparation;
import bsc.ejb.metadata.Framework;
import bsc.war.delegate.DelegateBSC;
import bsc.war.factory.Factory;
import bsc.war.model.Score;
import bsc.war.model.ScorePojo;
import bsc.war.service.BSCUtils;
import bsc.war.service.ScoreCardUtils;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.StringTokenizer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

/**
 *
 * @author Miguel Angel
 */
public class ShowPointerReport extends AbstractController {

    @Override
    protected ModelAndView handleRequestInternal(
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        String modelAndView= "";
        try {
            DelegateBSC delegate = (DelegateBSC) Factory.getBean("DelegateBSC");

            processRequestInternal(request, response, delegate);

           String typeReport= request.getParameter("typeReport");

            if (typeReport.equals("WEB")) {
                modelAndView = "pointerReportWeb";
            } else if (typeReport.equals("EXCEL")) {
                response.setContentType("application/vnd.ms-excel"); //Tipo de fichero.
                response.setHeader("Content-Disposition", "attachment;filename=\"report.xls\"");
                modelAndView = "pointerReportExcel";
            }

        } catch (Exception e) {
            logger.error("Catched exception", e);
        }
        return new ModelAndView(modelAndView);
    }

    public static void processRequestInternal(HttpServletRequest request,
            HttpServletResponse response, DelegateBSC delegate) {

        //Get the Person
        HttpSession session = request.getSession(true);
        Person person = (Person) session.getAttribute("person");

        //Get selected domains
        Long idScoreDomain = Long.parseLong(request.getParameter("idScoreDomain"));
        List<ScoreDomain> scoreDomains = new ArrayList();

        if (idScoreDomain == -1L) {
            scoreDomains = BSCUtils.getAllPersonScoreDomains(delegate, person);
        } else {
            scoreDomains.add(delegate.findScoreDomain(idScoreDomain));
        }

        //Get date
        Date dateReport = null;
        if (request.getParameter("dateReport") != null) {
            Integer tmpDate[] = new Integer[3];
            StringTokenizer dateTokens = new StringTokenizer(request.getParameter("dateReport"), "/");
            for (int i = 0; i < 3; i++) {
                tmpDate[i] = Integer.parseInt(dateTokens.nextToken());
            }

            dateReport = ScoreCardUtils.generateDate(/*lastDayOfMonth*/tmpDate[0], tmpDate[1], tmpDate[2]);
        }

        //Comparator of the pointer - Basado en los comparador que se estan utilizando
        //List<Comparator> comparators = delegate.findComparator(pointer);
        Framework framework = delegate.findFramework(Boolean.TRUE);
        Comparation comparation = ScoreCardUtils.getSystemComparation(request);


        //Get pointers - dimensionalCuts of each domian
        java.util.Map<ScoreDomain, List<DimensionalCut>> scoreDomainDimensionalCutsFirst = new HashMap<ScoreDomain, List<DimensionalCut>>();
        java.util.Map<ScoreDomain, List<DimensionalCut>> scoreDomainDimensionalCuts = new HashMap<ScoreDomain, List<DimensionalCut>>();
        java.util.Map<ScoreDomain, java.util.Map<DimensionalCut, ScorePojo>> scoreDomainDimensionalCutsScores = new HashMap<ScoreDomain, java.util.Map<DimensionalCut, ScorePojo>>();
        java.util.Map<ScoreDomain, java.util.Map<DimensionalCut, List<DimensionalCut>>> scoreDomainDimensionalCutsDCs = new HashMap<ScoreDomain, java.util.Map<DimensionalCut, List<DimensionalCut>>>();

        for (ScoreDomain scoreDomain : scoreDomains) {
            List<DimensionalCut> domainDimensionalCutsFirst = ScoreCardUtils.getDimensionalCutScoreCards(delegate, scoreDomain.getScoreView().getScoreCard());
            List<DimensionalCut> domainDimensionalCuts = ScoreCardUtils.getAllDimensionalCutScoreCards(delegate, scoreDomain.getScoreView().getScoreCard());

            scoreDomainDimensionalCutsFirst.put(scoreDomain, domainDimensionalCutsFirst);
            scoreDomainDimensionalCuts.put(scoreDomain, domainDimensionalCuts);

            java.util.Map<DimensionalCut, ScorePojo> dimensionalCutScore = new HashMap<DimensionalCut, ScorePojo>();
            java.util.Map<DimensionalCut, List<DimensionalCut>> dimensionalCutsDCs = new HashMap<DimensionalCut, List<DimensionalCut>>();

            for (DimensionalCut dimensionalCut : domainDimensionalCuts) {
                List<DimensionalCut> dimensionalCutDCs= ScoreCardUtils.getDimensionalCuts(delegate, dimensionalCut);

                Pointer pointer = dimensionalCut.getPointer();

                Comparator realComparator = delegate.findComparator(pointer, delegate.findComparation(framework, Comparation.Type.REAL));
                Comparator targetComparator = delegate.findComparator(pointer, comparation);

                //Score score = ScoreCardUtils.calculateScore(delegate, ScoreCardUtils.getSystemComparation(request), dimensionalCut, dateReport);
                Score score = ScoreCardUtils.calculatePointerScore(delegate, comparation, dimensionalCut.getPointer(), dateReport, dateReport, dimensionalCut);

                Double real = delegate.findComparatorDimensionalCut(realComparator, dateReport, dateReport, dimensionalCut);
                Double target = delegate.findComparatorDimensionalCut(targetComparator, dateReport, dateReport, dimensionalCut);

                if (real == null) {
                    real = 0.0;
                }

                if (target == null) {
                    target = 0.0;
                }

                ScorePojo scorePojo = (ScorePojo) Factory.getBean("ScorePojo");
                scorePojo.setReal(real);
                scorePojo.setTarget(target);
                scorePojo.setScore(score.getScore());
                scorePojo.setOutOfDate(score.isOutOfDate());


                //Color
                Colorimetry colorimetry = delegate.findColorimetry(dimensionalCut, score.getScore());
                String color= "FFFFFF";

                if(scorePojo.isOutOfDate()){
                    color="#DEDEDE";
                }else{
                    color= colorimetry.getColor();
                }
                scorePojo.setColor(color);

                dimensionalCutScore.put(dimensionalCut, scorePojo);
                dimensionalCutsDCs.put(dimensionalCut, dimensionalCutDCs);

            }
            scoreDomainDimensionalCuts.put(scoreDomain, domainDimensionalCuts);
            scoreDomainDimensionalCutsScores.put(scoreDomain, dimensionalCutScore);
            scoreDomainDimensionalCutsDCs.put(scoreDomain, dimensionalCutsDCs);
        }

        request.setAttribute("scoreDomains", scoreDomains);
        request.setAttribute("dateReport", dateReport);
        request.setAttribute("scoreDomainDimensionalCutsFirst", scoreDomainDimensionalCutsFirst);
        request.setAttribute("scoreDomainDimensionalCuts", scoreDomainDimensionalCuts);
        request.setAttribute("scoreDomainDimensionalCutsScores", scoreDomainDimensionalCutsScores);
        request.setAttribute("scoreDomainDimensionalCutsDCs", scoreDomainDimensionalCutsDCs);



        //Update members of all dimensional cuts
        //List of all DimensionalCuts
        List<DimensionalCut> dimensionalCuts = ScoreCardUtils.getDimensionalCuts(request, delegate);
        //Se obtiene los strings de los cuts
        java.util.Map<DimensionalCut, String> dimensionalCutsMembers = ScoreCardUtils.getDimensionalCutsMembersStrings(request, delegate, dimensionalCuts);

        request.setAttribute("dimensionalCutsMembers",dimensionalCutsMembers);


        //Update all the information for recursive


    }
}
